<?php
namespace app\admin\controller;


use app\admin\validate\AddMenu;
use app\admin\validate\EditMenu;
use think\Request;
use View;
use Db;
use Session;
use think\Exception;
use app\common\model\Menu as MenuModel;

use app\common\controller\BaseController;


class Menu extends BaseController
{

    public function __construct()
    {
        parent::__construct();

    }


    /*
     * 菜单列表
     */
    public function menulist(){

        $model = new MenuModel();
        $menuDatas = $model->getMenuRecursion();

        $this->assign('menuDatas', $menuDatas);
        return $this->fetch();

    }




    public function addmenu(){
        $model = new MenuModel();
        $topMenu = $model->getTopMenu();

        $this->assign('topMenu', $topMenu);
        return $this->fetch();
    }


    /*
     * 添加菜单操作
     */
    public function addmenuDo(Request $request){
        $model = new MenuModel();
        $param = $request->param();
        $validate= new AddMenu();
        try{
            $result = $validate->checkDo($param);
        }catch (Exception $e){
            return $this->error($e->getMessage());
        }

        if (!$result) {
            return $this->error($validate->getError());
        }


        if($model->addmenu($param)){

            return $this->success('添加成功', url('/admin/menu/menulist'));
        }


        return $this->error('添加失败');
    }



    /*
     * 删除菜单操作
     */
    public function delmenu(Request $request){
        $id = $request->param('id');
        $model = new MenuModel();
        try{
            if($model->delmenu($id)){
                return $this->success('删除成功', url('/admin/menu/menulist'));
            }
        }catch (Exception $e){
            return $this->error($e->getMessage());
        }


        return $this->error('删除失败');

    }


    /*
     * 菜单编辑
     */
    public function editmenu(Request $request){
        $id = $request->param('id');
        if(empty($id)){
            return $this->error('数据ID丢失！');
        }

        $model = new MenuModel();
        $topMenu = $model->getTopMenu();
        $info = $model->getInfoById($id);

        $this->assign('info', $info);
        $this->assign('topMenu', $topMenu);
        return $this->fetch();
    }

    /*
     * 编辑菜单操作
     */
    public function editmenuDo(Request $request){
        $model = new MenuModel();
        $param = $request->param();
        $validate= new EditMenu();
        try{
            $result = $validate->checkDo($param);
        }catch (Exception $e){
            return $this->error($e->getMessage());
        }
        if (!$result) {
            return $this->error($validate->getError());
        }

        if($model->editmenu($param)){
            return $this->success('更新成功', url('/admin/menu/menulist'));
        }
        return $this->error('更新失败');
    }


}